<template>
    <div id="login">
        <div class="form-wrap">
            <ul class="menu-tab">
                <li :class="{ current: current_menu == item.type }" v-for="item in tab_menu" :key="item.type"
                    @click="handleToggleMenu(item.type)">
                    {{ item.label }}
                </li>
            </ul>
            <el-form ref="formRef" :model="form" :rules="form_rules" status-icon>
                <el-form-item prop="username">
                    <label class="form-label" for="username">用户名</label>
                    <el-input id="username" placeholder="请输入用户名" v-model="form.username" clearable />
                </el-form-item>
                <el-form-item prop="password">
                    <label class="form-label" for="password">密码</label>
                    <el-input type="password" id="password" placeholder="请输入密码" v-model="form.password" show-password />
                </el-form-item>
                <el-form-item v-if="current_menu == 'register'" prop="password2">
                    <label class="form-label" for="password2">确认密码</label>
                    <el-input type="password" id="password2" placeholder="请输入确认密码" v-model="form.password2"
                        show-password />
                </el-form-item>
                <el-form-item prop="code">
                    <label class="form-label" for="code">验证码</label>
                    <el-row :gutter="20">
                        <el-col :span="14">
                            <el-input id="code" placeholder="请输入验证码" v-model="form.code" clearable />
                        </el-col>
                        <el-col :span="10">
                            <el-button class="el-button-block" type="success" @click="handleGetCatcha"
                                :disabled="button" :loading="code_button_loading">
                                {{ code_button_text }}
                            </el-button>
                        </el-col>
                    </el-row>
                </el-form-item>
                <el-form-item>
                    <el-button :type="submit_button_disabled ? 'info' : 'danger'" :disabled="submit_button_disabled"
                        :loading="submit_button_loading" class="el-button-block" @click="handleSubmitForm">
                        {{ current_menu == 'login' ? '登录' : '注册' }}
                    </el-button>
                </el-form-item>
            </el-form>
        </div>
    </div>
    <starry-sky :stars-count="1500" :distance="500" />
</template>
<script setup>
import { ref, reactive, toRefs, getCurrentInstance, onBeforeUnmount } from 'vue'
import sha1 from 'js-sha1'
import { validate_email, validate_password, validate_code } from '@/utils/validate'
import { GetCaptcha } from '@/api/common'
import { Register, Login } from '@/api/account'
import { useRouter } from 'vue-router'

// import { useCommonStore } from '@/stores/modules/common'
// const commonStore = useCommonStore()

import useStore from '@/stores'
const store = useStore()
const router = useRouter()
// import { ElMessage } from 'element-plus'
const formRef = ref(null)
const button = ref(false);
const code_button_loading = ref(false);
const count = ref(60);

// const { proxy } = getCurrentInstance()
// const handleGetCatcha = async () => {
//     // proxy.$axios.post('http://ibuy123.cn:8888/accounts/captcha', {
//     //     username: '1136238481@qq.com',
//     //     scene: 'register'
//     // })
//     //     .then(res => {
//     //         console.log('res', res);
//     //     })
//     const res = await GetCaptcha({
//         username: '1136238481@qq.com',
//         scene: 'register'
//     })
//     console.log('res', res);
// }


const handleGetCatcha = async () => {
    formRef.value.validateField(['username'], async (valid) => {
        if (valid) {
            code_button_text.value = '发送中'
            code_button_loading.value = true
            try {
                // const res = await GetCaptcha({
                //     username: form.value.username,
                //     scene: current_menu.value
                // })

                // pinia
                const res = await store.common.getCaptchaAction({
                    username: form.value.username,
                    scene: current_menu.value
                })
                console.log('res-----------', res);


                submit_button_disabled.value = false
                code_button_text.value = '获取验证码'
                ElMessage.success(res.msg)
                countdown()
            } catch (error) {
                code_button_loading.value = false
                code_button_text.value = '获取验证码'
            }
        }
    })

}
const countdown = () => {
    code_button_text.value = `倒计时${count.value}秒`
    button.value = true;
    count.value = 60;
    code_button_loading.value = false
    const timer = setInterval(() => {
        if (count.value > 0) {
            count.value--;
            code_button_text.value = `倒计时${count.value}秒`
        } else {
            code_button_text.value = `重新获取`
            code_button_loading.value = false
            clearInterval(timer);
            button.value = false;
        }
    }, 1000);
};

const handleToggleMenu = (val) => {
    current_menu.value = val
    // formRef.value.resetFields()
    formRef.value.clearValidate()
    submit_button_disabled.value = true
}

const validate_name_rules = (rule, value, callback) => {
    const valid = validate_email(value)
    if (value === '') {
        callback(new Error('请输入用户名'))
    } else {
        if (!valid) {
            callback(new Error('用户名格式不正确，应该为邮箱!'))
        }
        callback()
    }
}
const validate_password_rules = (rule, value, callback) => {
    const valid = validate_password(value)
    if (value === '') {
        callback(new Error('请输入密码'))
    } else {
        if (!valid) {
            callback(new Error('密码格式不正确，长度为6-20位之间，只包含数字和字母!'))
        }
        callback()
    }
}
const validate_password2_rules = (rule, value, callback) => {
    if (data.current_menu == 'login') {
        callback()
    }
    const pattern = /^(?!\D+$)(?![^a-zA-Z]+$)\S{6,20}$/
    const password = data.form.password
    if (value === '') {
        callback(new Error('请输入确认密码'))
    } else {
        if (!pattern.test(value)) {
            callback(new Error('密码格式不正确，长度为6-20位之间，只包含数字和字母!'))
        } else if (password && password != value) {
            callback(new Error('确认密码和密码输入不一致!'))
        } else {
            callback()
        }
    }
}
const validate_code_rules = (rule, value, callback) => {
    const valid = validate_code(value)
    if (value === '') {
        callback(new Error('请输入验证码'))
    } else {
        if (!valid) {
            callback(new Error('验证码格式不正确，长度为6位，只包含数字和字母!'))
        }
        callback()
    }
}

const data = reactive({
    tab_menu: [
        { type: 'login', label: '登录' },
        { type: 'register', label: '注册' },
    ],
    current_menu: 'login',
    form: {
        username: '',
        password: '',
        password2: '',
        code: ''
    },
    form_rules: {
        username: [
            { validator: validate_name_rules, trigger: 'change' },
        ],
        password: [
            { validator: validate_password_rules, trigger: 'change' },
        ],
        password2: [
            { validator: validate_password2_rules, trigger: 'change' },
        ],
        code: [
            { validator: validate_code_rules, trigger: 'change' },
        ],
    },
    // 注册和登录按钮
    submit_button_disabled: true, //禁用状态
    submit_button_loading: false, // 加载状态
    code_button_text: '获取验证码',
})
let { tab_menu, current_menu, form, form_rules, submit_button_disabled, submit_button_loading, code_button_text } = toRefs(data)
const reset = () => {
    formRef.value.resetFields()
    current_menu.value = 'login'
    // data.code_button_timer && clearInterval(data.code_button_timer)
    code_button_text.value = '获取验证码'
    submit_button_disabled.value = true
    submit_button_loading.value = false
}
// 登录
const handleLogin = async () => {
    const { username, password, code } = form.value
    // 密码加密
    const new_password = sha1(password)
    const requestData = {
        username,
        password: new_password,
        code
    }
    submit_button_loading.value = true
    try {
        const res = await store.app.loginAction(requestData)
        // store.app.updateToken(res.data.token)
        // store.app.updateUsername(res.data.username)
        ElMessage.success(res.msg)
        // reset()
        router.push({ name: 'Console' })
    } finally {
        submit_button_loading.value = false
    }
}
// 注册
const handleRegister = async () => {
    const { username, password, code } = form.value
    // 密码加密
    const new_password = sha1(password)
    const requestData = {
        username,
        password: new_password,
        code
    }
    submit_button_loading.value = true
    try {
        const res = await store.app.registerAction(requestData)
        ElMessage.success(res.msg)
        reset()
    } catch (error) {
        submit_button_loading.value = false
    }
}
const handleSubmitForm = () => {
    formRef.value.validate(valid => {
        console.log('valid', valid);
        current_menu.value == 'login' ? handleLogin() : handleRegister()
    })
}
</script>

<style lang="scss" scoped>
@import "@/assets/styles/main.scss";

#login {
    height: 100vh;
    // background-color: $bgColor;
    // position: relative;
    // z-index: -1;
}

.form-wrap {
    width: 320px;
    padding-top: 100px;
    margin: auto;
}

.menu-tab {
    text-align: center;

    li {
        display: inline-block;
        padding: 10px 24px;
        margin: 0 10px;
        color: #fff;
        font-size: 14px;
        border-radius: 5px;
        cursor: pointer;

        &.current {
            background: rgba(0, 0, 0, 0.1);
        }
    }
}

.form-label {
    display: block;
    color: #fff;
    font-size: 14px;
}
</style>